package org.springframework.mybatis.utils;

import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * <p>sql工具类，主要用于注解上sql语句的解析</p>
 * @author Bosen
 * @date 2021/9/27 21:16
 */
public class SqlUtils {
    /**
     * <p>匹配被"#{}"包裹的变量</p>
     */
    private static Pattern pattern = Pattern.compile("\\#\\{\\w+\\}");

    /**
     * <p>将sql语句中"#{}"包裹的变量替换成占位符"?"</p>
     */
    public static String occupied(String sql) {
        Matcher matcher = pattern.matcher(sql);
        while (matcher.find()) {
            sql = sql.replace(matcher.group(), "?");
        }
        return sql;
    }

    /**
     * <p>获取变量名称</p>
     */
    public static List<String> getParams(String sql) {
        Matcher matcher = pattern.matcher(sql);
        List<String> list = new ArrayList<>();

        while (matcher.find()) {
            list.add(matcher.group().trim()
                    .replace("#{", "")
                    .replace("}", ""));
        }
        return list;
    }
}
